package org.hshk.message.controller;

import com.google.gson.Gson;
import io.swagger.annotations.*;
import org.apache.log4j.Logger;
import org.hshk.message.BaseController;
import org.hshk.message.entity.CpMsgMember;
import org.hshk.message.entity.CpMsgMemberSign;
import org.hshk.message.outDto.OutMerchantList;
import org.hshk.message.repository.CpMsgMemberRepository;
import org.hshk.message.repository.CpMsgMemberSignRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by GaoChuang on 2017/3/27.
 */
@Api(value = "短信商户 API")
@RestController
@RequestMapping("/msgOrgs")

//商户查询，并分页显示

public class MsgOrgQueryController extends BaseController {
    private static final Logger log = Logger.getLogger(MsgOrgQueryController.class);

    @Autowired
    CpMsgMemberRepository cpMsgMemberRepository;
    @Autowired
    //短信厂家查询对象
            CpMsgMemberSignRepository cpMsgMemberSignRepository;
    //@Autowired
    //短信模版查询 单表对象
    //CpMsgTemplateRepository cpMsgTemplateRepository;
    //@Autowired
    //商户签名
    //CpMsgMemberSignMapper cpMsgMemberSignMapper;
    //@Autowired
    //模版查询接口
    //CpMsgTemplateMapper cpMsgTemplateMapper;
    //@Autowired
    //商户相关mapper
    // CpMsgMemberMapper cpMsgMemberMapper;
    BeanUtils beanUtils;
    //线程对象保存
    private static final ThreadLocal<Gson> local = new ThreadLocal<Gson>();

    private Gson getGson() {
        if (null == local.get()) {
            Gson gson = new Gson();
            local.set(gson);
        }
        return local.get();
    }

    @ApiOperation(value = "短信商户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "pageSize", value = "当前页显示条数", required = true, dataType = "int", paramType = "path"),
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "请求参数不正确"),
            @ApiResponse(code = 404, message = "请求路径没有或路径不正确")//
    })
    @ResponseBody
    @RequestMapping(value = "/page/{page}/pageSize/{pageSize}", method = RequestMethod.GET, produces = "application/json")


    public String msgOrgQuery(@PathVariable int page, @PathVariable int pageSize) {
        try {
            log.info("MsgMemberQueryController.msgOrgQuery" + "page" + page + "pageSize" + pageSize);

            Map<String, Object> paramMsg = new HashMap<String, Object>();
            if (0 == page) {
                paramMsg.put("page", "参数错误");
            }
            if (0 == pageSize) {
                paramMsg.put("pageSize", "参数错误");
            }
            if (0 != paramMsg.size()) {
                return getGson().toJson(paramMsg);
            }
            // int page1 = (page - 1) * pageSize;
            //计算总条数
            //int totalSize = cpMsgMemberMapper.findCount();
            /**
             * Creat by yyl
             * 2017年6月22日17:26:29
             */
            int totalSize = (int) cpMsgMemberRepository.count();

            //创建 短信商户类 集合
            List<OutMerchantList> outMerchantList = new ArrayList<OutMerchantList>();

            //调用mapper接口，分页查询商户信息（查询出了商户充值信息）
            //List<CpMsgMember> list = cpMsgMemberMapper.findById1AndId2(page1, pageSize);
            /**
             * Creat by yyl
             * 2017年6月22日17:42:15
             */
            //int page1 = page, size = pageSize;
            Sort sort = new Sort(Sort.Direction.ASC, "id");
            Pageable pageable = new PageRequest(page - 1, pageSize, sort);
            Page<CpMsgMember> list = cpMsgMemberRepository.findAll(pageable);
            //如果上面的list不符合规范的话
            // List<CpMsgMember> list = cpMsgMemberRepository.findAll(pageable).getContent();

            for (CpMsgMember cpMsgMember : list.getContent()) {
                //创建一个 短信商户 对象
                OutMerchantList outMerchantList1 = new OutMerchantList();
                beanUtils.copyProperties(cpMsgMember, outMerchantList1);
                //查询用户商家表，看看是否有使用短信厂商（根据商户id，品牌id，还有是否使用）
                CpMsgMemberSign cpMsgMemberSign = cpMsgMemberSignRepository.findByBrandIdAndOrgIdAndIsUsed(cpMsgMember.getBrandId(), cpMsgMember.getOrgId(), "Yes");
                if (null == cpMsgMemberSign) {
                    log.error("MsgOrgQueryController.msgOrgQuery " + "cpMsgMemberSign表参数不存在");
                    outMerchantList1.setFactoryId(0);
                    outMerchantList1.setMsgUsername("");
                    outMerchantList.add(outMerchantList1);
                    continue;
                }
                outMerchantList1.setFactoryId(cpMsgMemberSign.getFactoryId());
                outMerchantList1.setMsgUsername(cpMsgMemberSign.getMsgUsername());
                outMerchantList.add(outMerchantList1);
            }
            paramMsg.put("totalSize", totalSize);
            paramMsg.put("cpMember", outMerchantList);
            return getGson().toJson(paramMsg);
        } catch (Exception ex) {
            log.error("MsgMemberQueryController.msgOrgQuery" + ex.getMessage());
            ex.printStackTrace();
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("resultCode", "fail");
            resultMap.put("resultMsg", "失败");
            return getGson().toJson(resultMap);
        }
    }

}
